package cn.daniellee.plugin.wc.core;

import cn.daniellee.plugin.wc.Welcome;
import cn.daniellee.plugin.wc.model.PlayerData;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class WelcomeCore {

    public static ConcurrentHashMap<String, PlayerData> newPlayerCache = new ConcurrentHashMap<>();

    public static void handlePlayerJoin(Player player) {
        PlayerData playerData = Welcome.getInstance().getStorage().getPlayerDataByName(player.getName());
        // 查不到的是新玩家
        if (playerData == null) {
            long joinDate = System.currentTimeMillis();
            // 添加玩家数据
            playerData = new PlayerData(player.getName());
            playerData.setJoinDate(joinDate);
            Welcome.getInstance().getStorage().addPlayerData(playerData);
            // 添加到缓存
            WelcomeCore.newPlayerCache.put(player.getName(), playerData);
            // 发送更新消息
            if (Welcome.getInstance().isBungeeCord()) {
                Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Welcome.getInstance(), () -> {
                    WelcomeCore.sendNewbieMessage(player, joinDate);
                }, 5);

            }
            // 广播欢迎语
            WelcomeCore.broadcastWelcome(player.getName());
        }
    }

    public static void handleWelcome(Player welcomer, String welcomee, boolean fromCommand) {
        PlayerData playerData = newPlayerCache.get(welcomee);
        // 不是新玩家
        if (playerData == null) {
            welcomer.sendMessage((Welcome.getInstance().getPrefix() + Welcome.getInstance().getConfig().getString("message.not-newbie", "&ePlayer &d{name} &edoes not exist or is no longer a new player!").replace("{name}", welcomee)).replace("&", "§"));
            return;
        }
        // 不可以欢迎自己
        if (welcomer.getName().equals(playerData.getName())) {
            welcomer.sendMessage((Welcome.getInstance().getPrefix() + Welcome.getInstance().getConfig().getString("message.cant-self", "&eOf cause, welcome yourself!")).replace("&", "§"));
            return;
        }
        if (System.currentTimeMillis() - playerData.getJoinDate() > Welcome.getInstance().getPeriod()) {
            welcomer.sendMessage((Welcome.getInstance().getPrefix() + Welcome.getInstance().getConfig().getString("message.out-dated", "&eWelcome &d{name} &etime is up!").replace("{name}", welcomee)).replace("&", "§"));
            return;
        }
        // 检查是否已经欢迎过了
        if (playerData.getWelcomed().contains(welcomer.getName())) {
            welcomer.sendMessage((Welcome.getInstance().getPrefix() + Welcome.getInstance().getConfig().getString("message.already-welcomed", "&eYou've already welcomed &d{name} &e!").replace("{name}", welcomee)).replace("&", "§"));
            return;
        } else {
            // 缓存里没欢迎过的话，去数据库检查
            if (Welcome.getInstance().getStorage().checkWelcomed(welcomee, welcomer.getName())) {
                welcomer.sendMessage((Welcome.getInstance().getPrefix() + Welcome.getInstance().getConfig().getString("message.already-welcomed", "&eYou've already welcomed &d{name} &e!").replace("{name}", welcomee)).replace("&", "§"));
                // 更新数据
                playerData.getWelcomed().add(welcomer.getName());
                return;
            }
            // 没欢迎过，正常执行
        }
        welcomer.chat("▶" + Welcome.getInstance().getMessages().get(new Random().nextInt(Welcome.getInstance().getMessages().size())).replace("{name}", welcomee).replace("&", "§"));
        // 更新数据
        playerData.getWelcomed().add(welcomer.getName());
        Welcome.getInstance().getStorage().addWelcomed(welcomee, welcomer.getName());
        // 发送更新消息
        if (Welcome.getInstance().isBungeeCord()) sendWelcomedMessage(welcomer, playerData.getName());
        // 发送奖励
        int rewardMin = Welcome.getInstance().getConfig().getInt("setting.welcome-reward.min", 100);
        int rewardMax = Welcome.getInstance().getConfig().getInt("setting.welcome-reward.max", 300);
        int rewardAmount = new Random().nextInt(rewardMax - rewardMin + 1) + rewardMin;
        Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Welcome.getInstance(), () -> {
            Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), Welcome.getInstance().getConfig().getString("setting.reward-command", "money give {name} {amount}").replace("{name}", welcomer.getName()).replace("{amount}", String.valueOf(rewardAmount)));
        }, 5);
        welcomer.sendMessage((Welcome.getInstance().getPrefix() + Welcome.getInstance().getConfig().getString("message.reward-notice", "&eThanks for your warm welcome, &b${amount} &erewards have been issued to you!").replace("{amount}", String.valueOf(rewardAmount))).replace("&", "§"));
    }

    // 广播欢迎信息
    public static void broadcastWelcome(String name) {
        TextComponent welcomeMessage = new TextComponent((Welcome.getInstance().getPrefix() + Welcome.getInstance().getConfig().getString("message.welcome-notice", "&eLined up to welcome new players &d{name}&e!").replace("{name}", name)).replace("&", "§"));
        TextComponent sendButton = new TextComponent(Welcome.getInstance().getConfig().getString("message.send-button", "&c [Click me to send welcome message]").replace("&", "§"));
        sendButton.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/welcome {name}".replace("{name}", name)));
        String keywords = String.join("/", Welcome.getInstance().getKeywords());
        sendButton.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(Welcome.getInstance().getConfig().getString("message.button-tips", "You can also send &b{keywords} &e+ player name to welcome!").replace("{keywords}", keywords).replace("&", "§")).create()));
        Bukkit.spigot().broadcast(welcomeMessage, sendButton);
    }

    // 发送BC广播
    public static void sendNewbieMessage(Player player, long joinDate) {
        ByteArrayDataOutput out = ByteStreams.newDataOutput();
        out.writeUTF("Forward");
        out.writeUTF("ALL");
        out.writeUTF("Welcome");
        ByteArrayOutputStream msgBytes = new ByteArrayOutputStream();
        DataOutputStream msgOut = new DataOutputStream(msgBytes);
        try {
            msgOut.writeUTF("Newbie");
            msgOut.writeUTF(player.getName());
            msgOut.writeLong(joinDate);
        } catch (IOException ignored){}
        out.writeShort(msgBytes.toByteArray().length);
        out.write(msgBytes.toByteArray());
        player.sendPluginMessage(Welcome.getInstance(), "BungeeCord", out.toByteArray());
    }

    public static void sendWelcomedMessage(Player player, String welcomee) {
        ByteArrayDataOutput out = ByteStreams.newDataOutput();
        out.writeUTF("Forward");
        out.writeUTF("ALL");
        out.writeUTF("Welcome");
        ByteArrayOutputStream msgBytes = new ByteArrayOutputStream();
        DataOutputStream msgOut = new DataOutputStream(msgBytes);
        try {
            msgOut.writeUTF("Welcomed");
            msgOut.writeUTF(welcomee);
            msgOut.writeUTF(player.getName());
        } catch (IOException ignored){}
        out.writeShort(msgBytes.toByteArray().length);
        out.write(msgBytes.toByteArray());
        player.sendPluginMessage(Welcome.getInstance(), "BungeeCord", out.toByteArray());
    }

}
